<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>国标文件分析系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 2rem;
            text-align: center;
            background-color: #f8f9fa;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .upload-area:hover {
            border-color: #0d6efd;
            background-color: #e9ecef;
        }
        .result-card {
            transition: all 0.3s ease;
        }
        .result-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .progress {
            height: 0.5rem;
        }
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
        .toast {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .toast-header {
            background-color: #28a745;
            color: white;
            border-radius: 8px 8px 0 0;
        }
        .toast-body {
            padding: 1rem;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .loading-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }
    </style>
</head>
<body class="bg-light">
    <!-- 添加Toast容器 -->
    <div class="toast-container"></div>
    
    <!-- 添加加载遮罩层 -->
    <div id="loadingOverlay" class="loading-overlay d-none">
        <div class="loading-content">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <h5>正在解析文件，请稍候...</h5>
        </div>
    </div>
    
    <div class="container py-5">
        <h1 class="text-center mb-5">国标文件分析系统</h1>
        
        <!-- 上传区域 -->
        <div class="row justify-content-center mb-5">
            <div class="col-md-8">
                <div id="uploadArea" class="upload-area">
                    <i class="bi bi-cloud-upload fs-1 text-primary mb-3"></i>
                    <h4>拖拽文件到此处或点击上传</h4>
                    <p class="text-muted">支持PDF文件</p>
                    <input type="file" id="fileInput" accept=".pdf" class="d-none">
                    <div id="uploadProgress" class="progress d-none mt-3">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 分析结果区域 -->
        <div id="resultArea" class="row g-4">
            <!-- 结果卡片将在这里动态添加 -->
        </div>
    </div>

    <div class="container mt-5">
        <h4>文件上传记录</h4>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>上传时间</th>
                        <th>文件号</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="fileRecordsList"></tbody>
            </table>
        </div>
        <nav>
            <ul class="pagination justify-content-center" id="pagination"></ul>
        </nav>
    </div>

    <!-- 新增分析结果列表 -->
    <div class="container mt-5">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4>分析结果列表</h4>
        </div>
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>国标号</th>
                        <th>国标名称</th>
                        <th>分析时间</th>
                        <th>文件页数</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="analysisResultsList"></tbody>
            </table>
        </div>
    </div>

    <!-- 添加模态框组件 -->
    <div class="modal fade" id="analysisDetailModal" tabindex="-1" aria-labelledby="analysisDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="analysisDetailModalLabel">分析结果详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <h6>国标号：<span id="modalStandardNo"></span></h6>
                        <h6>国标名称：<span id="modalStandardName"></span></h6>
                        <hr>
                        <h6>分析结果：</h6>
                        <div id="modalFileResult" class="border p-3 bg-light"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 添加显示Toast的函数
        function showToast(message, type = 'success') {
            const toastContainer = document.querySelector('.toast-container');
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            const headerClass = type === 'success' ? 'bg-success' : 'bg-danger';
            
            toast.innerHTML = `
                <div class="toast-header ${headerClass} text-white">
                    <strong class="me-auto">${type === 'success' ? '成功' : '错误'}</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast, {
                autohide: true,
                delay: 3000
            });
            bsToast.show();
            
            // 自动移除
            toast.addEventListener('hidden.bs.toast', () => {
                toast.remove();
            });
        }

        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');
            const uploadProgress = document.getElementById('uploadProgress');
            const resultArea = document.getElementById('resultArea');

            // 处理拖拽上传
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#0d6efd';
                uploadArea.style.backgroundColor = '#e9ecef';
            });

            uploadArea.addEventListener('dragleave', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#ccc';
                uploadArea.style.backgroundColor = '#f8f9fa';
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    handleFileUpload(files[0]);
                }
            });

            // 处理点击上传
            uploadArea.addEventListener('click', () => {
                fileInput.click();
            });

            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    handleFileUpload(e.target.files[0]);
                }
            });

            function handleFileUpload(file) {
                if (file.type !== 'application/pdf') {
                    showToast('请上传PDF文件！', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('file', file);

                // 显示进度条
                uploadProgress.classList.remove('d-none');
                const progressBar = uploadProgress.querySelector('.progress-bar');
                progressBar.style.width = '0%';

                // 模拟上传进度
                let progress = 0;
                const progressInterval = setInterval(() => {
                    progress += 10;
                    if (progress <= 90) {
                        progressBar.style.width = progress + '%';
                    }
                }, 200);

                // 发送文件到后端
                fetch('/api/analyze', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('上传失败');
                    }
                    return response.json();
                })
                .then(data => {
                    clearInterval(progressInterval);
                    progressBar.style.width = '100%';
                    setTimeout(() => {
                        uploadProgress.classList.add('d-none');
                        progressBar.style.width = '0%';
                    }, 500);
                    
                    if (data.code !== 200) {
                        showToast(data.message, 'error');
                    } else {
                        // addResultCard(data.data);
                        loadFileRecords();
                        showToast(data.message);
                    }
                })
                .catch(error => {
                    clearInterval(progressInterval);
                    uploadProgress.classList.add('d-none');
                    showToast(error.message, 'error');
                });
            }

            function    addResultCard(data) {
                const card = document.createElement('div');
                card.className = 'col-md-6 col-lg-4';
                card.innerHTML = `
                    <div class="card result-card h-100">
                        <div class="card-body">
                            <h5 class="card-title text-primary">${data.standardNo || '未知国标号'}</h5>
                            <h6 class="card-subtitle mb-2 text-muted">${data.standardName || '未知国标名称'}</h6>
                            <div class="mt-3">
                                <h6 class="text-danger">错误原因：</h6>
                                <p class="card-text">${data.errorReason || '无'}</p>
                            </div>
                        </div>
                        <div class="card-footer bg-transparent">
                            <small class="text-muted">分析时间：${new Date().toLocaleString()}</small>
                        </div>
                    </div>
                `;
                resultArea.insertBefore(card, resultArea.firstChild);
            }

            // 添加分析结果到列表
            function addAnalysisResult(data) {
                const tbody = document.getElementById('analysisResultsList');
                // 清空现有的结果
                tbody.innerHTML = '';
                
                // 启用导出按钮
                document.getElementById('exportExcelBtn').disabled = false;
                
                // 保存当前分析结果到全局变量，用于导出
                window.currentAnalysisResults = data;
                
                // 如果是数组，遍历添加每个结果
                if (Array.isArray(data)) {
                    data.forEach(item => {
                        const tr = document.createElement('tr');
                        const escapedItem = encodeURIComponent(JSON.stringify(item));
                        tr.innerHTML = `
                            <td>${item.a100 || '未知国标号'}</td>
                            <td>${item.a298 || '未知国标名称'}</td>
                            <td>${new Date().toLocaleString()}</td>
                            <td>${item.filePage || '-'}</td>
                            <td>${item.fileStatus === 1 ? '<span class="text-success">正确</span>' : '<span class="text-danger">错误</span>'}</td>
                            <td>
                                <button class="btn btn-info btn-sm" onclick="viewAnalysisDetail('${escapedItem}')">查看详情</button>
                            </td>
                        `;
                        tbody.appendChild(tr);
                    });
                }
            }


            
            // 添加查看详情的函数
            window.viewAnalysisDetail = function(itemStr) {
                try {
                    const decodedStr = decodeURIComponent(itemStr);
                    const item = JSON.parse(decodedStr);
                    console.log('Parsed item:', item); // 添加调试日志
                    
                    // 更新模态框内容
                    document.getElementById('modalStandardNo').textContent = item.a100 || '未知国标号';
                    document.getElementById('modalStandardName').textContent = item.a298 || '未知国标名称';
                    
                    // 格式化显示fileResult
                    let fileResultContent = '';
                    try {
                        // 尝试解析JSON
                        const resultObj = JSON.parse(item.fileResult);
                        fileResultContent = JSON.stringify(resultObj, null, 2);
                    } catch (e) {
                        // 如果不是JSON格式，直接显示原文
                        fileResultContent = item.fileResult || '暂无分析结果';
                    }
                    
                    document.getElementById('modalFileResult').innerHTML = `<pre style="white-space: pre-wrap; word-break: break-word;">${fileResultContent}</pre>`;
                    
                    // 获取模态框元素
                    const modalElement = document.getElementById('analysisDetailModal');
                    
                    // 确保之前的模态框实例被销毁
                    const oldModal = bootstrap.Modal.getInstance(modalElement);
                    if (oldModal) {
                        oldModal.dispose();
                    }
                    
                    // 创建新的模态框实例并显示
                    const modal = new bootstrap.Modal(modalElement, {
                        keyboard: true,
                        backdrop: true
                    });
                    modal.show();
                } catch (error) {
                    console.error('Error showing modal:', error);
                    console.error('Item string received:', itemStr); // 添加调试日志
                    showToast('显示详情时出错', 'error');
                }
            };
            // 修改解析文件的函数
            window.analyzeFile = function(fileId) {
                const loadingOverlay = document.getElementById('loadingOverlay');
                loadingOverlay.classList.remove('d-none');
                
                const button = document.querySelector(`button[data-file-id="${fileId}"]`);
                if (button.innerText === '分析') {
                    // 更新加载提示文本
                    document.querySelector('#loadingOverlay h5').textContent = '正在分析文件，请稍候...';
                    // 发送分析请求
                    fetch(`/api/filerecords/analyze/${fileId}`)
                    .then(response => {
                            if (!response.ok) {
                                throw new Error('网络响应失败: ' + response.status);
                            }
                            return response.json();
                        })
                    .then(data => {
                        loadingOverlay.classList.add('d-none');
                        if (data.code !== 200) {
                            showToast(data.message || '分析失败', 'error');
                        } else {
                            // 添加到分析结果列表
                            addAnalysisResult(data.data);
                            showToast('文件分析成功！已找到 ' + (Array.isArray(data.data) ? data.data.length : 1) + ' 个国标', 'success');
                            // 更新按钮状态
                            button.innerText = '已分析';
                            button.disabled = true;
                            button.classList.remove('btn-primary');
                            button.classList.add('btn-secondary');
                        }
                    })
                    .catch(error => {
                        console.log(error)
                        loadingOverlay.classList.add('d-none');
                        showToast(`分析错误: ${error.message}`, 'error');
                    });
                } else {
                    // 更新加载提示文本
                    document.querySelector('#loadingOverlay h5').textContent = '正在解析文件，请稍候...';
                    
                    // 发送解析请求
                    fetch(`/api/analyze/${fileId}`)
                    .then(response => response.json())
                    .then(data => {
                        loadingOverlay.classList.add('d-none');
                        if (data.code !== 200) {
                            showToast(data.message || '解析失败', 'error');
                        } else {
                            addResultCard(data.data);
                            loadFileRecords(currentPage); // 重新加载文件列表以更新状态
                            showToast(data.message || '解析成功', 'success');
                            // 更新按钮状态
                            button.innerText = '分析';
                            button.classList.remove('btn-secondary');
                            button.classList.add('btn-primary');
                        }
                    })
                    .catch(error => {
                        loadingOverlay.classList.add('d-none');
                        showToast(`解析错误: ${error.message}`, 'error');
                    });
                }
            };


            //下载文件
            window.upload = function(fileId) {
                // 调用后端导出接口
                fetch('/api/standard/export-excel/'+fileId, {
                    method: 'get',
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('导出失败');
                        }
                        return response.blob();
                    })
                    .then(blob => {
                        // 隐藏加载遮罩
                        loadingOverlay.classList.add('d-none');

                        // 创建下载链接
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = '国标分析结果_' + new Date().toISOString().slice(0, 10) + '.xlsx';
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);

                        showToast('Excel导出成功');
                    })
                    .catch(error => {
                        loadingOverlay.classList.add('d-none');
                        showToast(`导出错误: ${error.message}`, 'error');
                    });
            };



            // 更新文件记录列表中的按钮
            function updateFileRecordsList(records) {
                const tbody = document.getElementById('fileRecordsList');
                tbody.innerHTML = records.map(record => `
        <tr>
            <td>${record.fileName}</td>
            <td>${new Date(record.uploadTime).toLocaleString()}</td>
            <td>${record.fileId}</td>
            <td>${record.status === 1 ? '<span class="text-success">上传成功</span>' :
                    record.status === 2 ? '<span class="text-primary">解析成功</span>' :
                    record.status === 3 ? '<span class="text-primary">分析完成</span>' : '<span class="text-danger">上传失败</span>'}</td>
            <td>
                <button id="exportExcelBtn" class="btn btn-primary btn-sm"
                        onclick="analyzeFile('${record.fileId}')"
                        data-file-id="${record.fileId}">
                        ${record.status === 1 ? '解析' : '分析'}
                </button>
                <button class="btn btn-primary btn-sm"
                        onclick="upload('${record.id}')">
                <i class="bi bi-file-earmark-excel"></i> 导出Excel
                </button>

            </td>
        </tr>
    `).join('');
            }

            // 加载文件记录列表（分页）
            function loadFileRecords(page = 1) {
                fetch(`/api/file-records/list?current=${page}&size=10`)
                    .then(response => response.json())
                    .then(data => {

                            updateFileRecordsList(data.records);
                            updatePagination(data.total, 10, page);

                    })
                    .catch(error => {
                        console.error('加载文件记录失败:', error);
                        showToast('加载文件记录失败', 'error');
                    });
            }

            // 更新分页
            function updatePagination(total, pageSize, currentPage) {
                const totalPages = Math.ceil(total / pageSize);
                const pagination = document.getElementById('pagination');
                let paginationHtml = '';
                
                // 上一页按钮
                paginationHtml += `
                    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="return ${currentPage > 1 ? 'loadFileRecords(' + (currentPage - 1) + ')' : 'false'}">&laquo;</a>
                    </li>
                `;
                
                // 页码按钮
                for (let i = 1; i <= totalPages; i++) {
                    paginationHtml += `
                        <li class="page-item ${currentPage === i ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="return loadFileRecords(${i})">${i}</a>
                        </li>
                    `;
                }
                
                // 下一页按钮
                paginationHtml += `
                    <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="return ${currentPage < totalPages ? 'loadFileRecords(' + (currentPage + 1) + ')' : 'false'}">&raquo;</a>
                    </li>
                `;
                
                pagination.innerHTML = paginationHtml;
            }

            // 初始加载
            loadFileRecords(1);
        });
    </script>
</body>
</html>
